#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
import datetime
from utils.config import Config
from loguru import logger


mysql_conf = Config.mirror_params
mounth = '%02d' % datetime.date.today().month

#查询数据库
def select_db(sql):
    try:
        conn = pymysql.connect(host = mysql_conf['host'],
                               port = int(mysql_conf['port']),
                               user = mysql_conf['user'],
                               password = mysql_conf['password'],
                               database = mysql_conf['db'])
        cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
        cur.execute(sql)
        result = cur.fetchall()
        conn.commit()
        # cur.close()
        # conn.close()
        return result
    except Exception as e:
        logger.info(f"sql - select - error - reason - {e}")
        conn.rollback()
    finally:
        cur.close()
        conn.close()


def insert_update_db(sql):
    try:
        conn = pymysql.connect(host = mysql_conf['host'],
                               port = int(mysql_conf['port']),
                               user = mysql_conf['user'],
                               password = mysql_conf['password'],
                               database = mysql_conf['db'])
        cur = conn.cursor()
        #cur.executemany(sql, args)
        cur.execute(sql)
        conn.commit()

    except Exception as e:
        logger.info(f"sql - update - error - reason - {e}")
        conn.rollback()
    finally:
        cur.close()
        conn.close()


#查询日期内的用户id
def get_send_email(end_time):
    # sql=f"""
    #     SELECT
    #        *
    #     FROM
    #         dlz_send_emai_list
    #     WHERE
    #         is_send=1
    #         AND create_time < '{end_time}'
    #             """
    sql=f"""
        SELECT
           *
        FROM
            dlz_send_emai_list
        WHERE
            is_send=1
            AND create_time < '{end_time} limit 950'
                """
    print(sql)
    res = select_db(sql)
    return res


def update_send_status(id,is_send):
    try:
        sql = f"""update dlz_send_emai_list set 
        is_send = {is_send}
        where id = {id} """
        insert_update_db(sql)
        logger.info(f"update data to mysql for {id}")
    except Exception as e:
        logger.info(f"fail to update data to mysql for {id} --{e}")

